<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="../taglib.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>
<script type="text/javascript" src="${ctx}res/js/MD5.js"></script>
</head>
<body>
	<div class="search-wrap">
		<form id="schForm">
	       	<table>
				<tr>
					<td>用户名:</td><td id="txtUsernameSch"><input type="text" class="control-text" name="usernameSch"></td>
					<td>
						<div id="btnSch"><button  type="button" id="schBtn" class="button button-primary">搜索</button></div>
					</td>
				</tr>
			</table>
		</form>
	</div>
   
	<div class="grid-bar">
		<button  type="button" id="addNewUser" class="button button-primary">新增用户</button>
	</div>
   
	<div id="grid"></div>
   
	<div id="crudWin" style="display: none;">
		<form id="form">
	   		<table class="insert-tab" width="100%">
	        	<tbody>
	                <tr>
	                    <th><i class="require-red">*</i>用户名：</th>
	                    <td id="txtUsername"><input name="username" type="text"
	                    rules="[{rule:{notNull:true},errorMsg:'请输入用户名'}
							,{rule:{minLength:6,maxLength:16},errorMsg:'用户名长度必须为6~16'}
							]"
	                    /></td>
	                </tr>
	                <tr>
	                    <th><i class="require-red">*</i>密码：</th>
	                    <td id="txtPassword"><input name="password" type="password"
	                    rules="[{rule:{notNull:true},errorMsg:'请输入密码'}
							,{rule:{minLength:5,maxLength:20},errorMsg:'密码长度必须为5~20'}
							]"
	                    /></td>
	                </tr>
	         	</tbody>
	         </table>
         </form>
   </div>

<script type="text/javascript" src="js/SelectRoleWin.js?v=<%=Math.random()%>"></script>
<script type="text/javascript">
VUI.use(['PageForm'],function(){
	var TYPE_ADD = 'add', TYPE_EDIT = 'update',TYPE_REMOVE = 'remove';
	var ROLE_TYPE = {
		PERSON : 1
		,GROUP : 2
	}
	
	var UserStateEnum = {OPEN:1,CLOSE:0};
	
	var UserState = {};
	UserState[UserStateEnum.OPEN] = '<span class="label label-success">启用</span>';
	UserState[UserStateEnum.CLOSE] = '<span class="label label-important">禁用</span';
    
	var listUrl = ctx + 'listRUser.do'; // 查询
	var addUrl = ctx + 'addRUser.do'; // 添加
	var resetUserPasswordUrl = ctx + 'resetUserPassword.do';
	var addRoleUrl = ctx + 'addUserRole.do';
	var delRoleUrl = ctx + 'delUserRole.do';
	var optStateUrl = ctx + 'optState.do';
	
	var schForm,pageForm,grid,win;	
	
	var roleHandlers = {
		selectHandler:function(item){
			postAddRole(item);
		}
	  	,unselectHandler:function(item){
	  		postDelRole(item);
	  	}
	}
	
	grid = new VUI.Grid({
		renderId:'grid'
		,url:listUrl
		,method:'post'
		,requestSortName:'field'
		,requestOrderName:'direction'
		,striped:true // 斑马线
		,pagination :true
		,rownumbers :true
		,columns : [ [
			{title:'用户名',field:'username'}
            ,{title:'用户角色',field:'',sortable:false,formatter:function(val,obj){
                	return roleFormatter(obj);
                }}
            , {title:'添加时间',field:'addTime',sortable:true}
            , {title:'最后登录时间',field:'lastLoginDate',sortable:true}
            , {title:'状态',field:'state',sortable:false,formatter:function(val){
            	return UserState[val];
            }}
            ,{title:'操作',field:'',sortable:false,formatter : function(value,obj){
           	  var stateOpenStr = '<span class="grid-command btn-openState">启用</span>';
           	  var stateCloseStr = '<span class="grid-command btn-closeState">禁用</span>';
           	  
           	  var stateStr = obj.state == UserStateEnum.OPEN ? stateCloseStr : stateOpenStr;
           	  
       	      var resetPswdStr = '<span class="grid-command btn-resetPswd">重置密码</span>';
              var setRoleStr = '<span class="grid-command btn-setRole">设置角色</span>';
              return RightUtil.auth('grid_optState',stateStr,'') + RightUtil.auth('grid_resetPwsd',resetPswdStr,'') 
              	+ RightUtil.auth('grid_setRole',setRoleStr,'');
            }}
			] 
		]
	});
	
	grid.on('ClickCell',function(e){
		var sender = $(e.target); // $target即<span>
		var record = e.row;
    	if(sender.hasClass('btn-resetPswd')){
        	resetPassword(record);
    	}
    	if(sender.hasClass('btn-setRole')){
	        addRole(record);
    	}
    	if(sender.hasClass('btn-openState')){
        	record.state = UserStateEnum.OPEN;
        	optState(record);
    	}
    	if(sender.hasClass('btn-closeState')){
        	record.state = UserStateEnum.CLOSE;
        	optState(record);
    	}
	});
	
	
	form = new VUI.Form({
		formId:'form'
	});
	
	
	schForm = new VUI.Form({
		formId:'schForm'
	});
	
	win = new VUI.Dialog({
		contentId:'crudWin'
		,title:'编辑'
		,width:400
		,onOk:function() {
			pageForm.save({
				onSubmit:function(data){
				var ret = this.validate();
				if(ret) {
					var passwordVal = data.password;
					data.password = faultylabs.MD5(passwordVal);
				}
				return ret;
			}});
		}
	});
	
	pageForm = new VUI.PageForm({
		formId:'form'
		,grid:grid
		,win:win
		,crudUrl:{
			add:addUrl
		}
	});
	
	$('#addNewUser').click(function(){
		pageForm.add();
	});
	
	$('#schBtn').on('click',function(ev){
        ev.preventDefault();
        search();
 	});
	
	function add(){
		form.clear();
		win.setTitle('添加')
		win.show();
    }
	
	function search() {
    	var param = schForm.getData();
    	grid.load(param);
    }
	
	function optState(record) {
    	var optName = record.state == UserStateEnum.OPEN ?　'启用' : '禁用';
    	
    	VUI.Msg.confirm('确认',"确定" + optName + record.username+"吗?",function(r){
    		if(r) {
	    		Action.jsonAsyncActByData(optStateUrl,record,function(e){
	    			Action.execResult(e,function(){
	    				grid.reload();
	    			});
				});
    		}
       	});
    }
	
	function resetPassword(row){
		VUI.Msg.confirm('重置密码',"确定给"+row.username+"重置密码吗?",function(r){
			if(r) {
	    		Action.jsonAsyncActByData(resetUserPasswordUrl,row,function(e){
	    			Action.execResult(e,function(){
	    				grid.reload();
	    				VUI.Msg.alert('重置密码','密码重置成功,新密码为:<br><strong style="font-size:14px;color:red;">' + e.message + '</strong>');
	    			});
				});
			}
       	});
    }
	
	function addRole(row) {
    	var userRoles = row.roles;
    	var userId = row.userId;
   		var roleIds = [];
   		for(var i=0,len=userRoles.length; i<len; i++) {
   			roleIds.push(userRoles[i].roleId);
   		}
   		SelectRoleWin.showPerson(roleIds,userId,roleHandlers);
    }
	
	function roleFormatter(rowData){
    	var roles = rowData.roles;
    	if(!roles || roles.length == 0){
    		return '<span style="color:red;">未分配角色</span>';
    	}
    	
    	var roleNameHtml = [];
    	for(var i=0,len=roles.length; i<len; i++) {
    		roleNameHtml.push(roles[i].roleName);
    	}
    	
    	// 所有的角色名
    	var roleNameStr = roleNameHtml.join('、');
    	
    	var resultStr = ['<div title="'+roleNameStr+'">'];
    	
    	if(roleNameHtml.length > 6){ 
    		for(var i=0; i<6; i++) {
    			resultStr.push(roleNameHtml[i] + "、");
    		}
    		resultStr.push('...');
    	}else{
    		resultStr.push(roleNameStr);
    	}
    	
    	resultStr.push('</div>');
    	
    	return resultStr.join('');
    }
	
	function postAddRole(item) {
    	item.url = addRoleUrl;
    	setUserRole(item);
    }
    
    function postDelRole(item) {
    	item.url = delRoleUrl;
    	setUserRole(item);
    }
    
	function setUserRole(param) {
		var roleId = param.roleId;
		var url = param.url;
		
		var data = {
			userId:param.extKey
			,roleId:roleId
			,roleType:param.roleType
			,groupId:param.groupId
		}
		
		Action.post(url,data,function(e){
			Action.execResult(e,function(){
				grid.reload();
			});
		});
	}
	
});
</script>
</body>
</html>